package net.midnighttd.engine.view.sprite;

import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.awt.*;

import net.midnighttd.engine.view.sprite.SpriteList;

/**
 * Author: Adam Scarr
 * Date: 19/04/2009
 * Time: 5:47:50 PM
 */
public class SpriteManager {
    private HashMap<String, Sprite> sprites = new HashMap<String, Sprite>();
    private Map<Integer, SpriteList> activeSprites = new TreeMap<Integer, SpriteList>();

    /**
     * Imports a set of sprites from an xml file.
     * @param e XML Element to get data from.
     */
    public void loadFromXML(Element e) {
        NodeList sprites = e.getElementsByTagName("sprite");
        for(int i = 0; i < sprites.getLength(); i++) {
            XMLSprite s = new XMLSprite((Element)sprites.item(i));

            if(this.sprites.containsKey(s.getName())) {
                throw new Error("XMLSprite " + s.getName() + "  overlaps with existing sprite");
            }

            this.sprites.put(s.getName(), s);
        }
    }

    public synchronized void updateAll() {
        for(SpriteList list: activeSprites.values()) {
            list.updateAll();
        }
    }

    /**
     * Gets a copy of a named sprite.
     * @param spritename    The name of the sprite
     * @return              The sprite identified by spritename.
     */
    public Sprite getSprite(String spritename) {
        Sprite orig = sprites.get(spritename);
        if(orig == null) throw new Error("Could not find sprite called " + spritename);
        Sprite copy = orig.copy();
        add(copy);
        return copy; 
    }

    public Sprite getTemplateSprite(String spritename) {
        Sprite orig = sprites.get(spritename);
        if(orig == null) throw new Error("Could not find sprite called " + spritename);
        Sprite copy = orig.copy();
        return copy;
    }



    public synchronized void add(Sprite s) {
        SpriteList list = activeSprites.get(s.getZ());

        if(list == null) {
            list = new SpriteList();
            activeSprites.put(s.getZ(), list);
        }

        list.add(s);
    }

    public synchronized void remove(Sprite s) {

        SpriteList list = activeSprites.get(s.getZ());

        if(list != null) {
            list.remove(s);
        }
    }

    public synchronized void drawAll(Graphics g) {
        for(SpriteList list: activeSprites.values()) {
            list.drawAll(g);
        }
    }
}
